package Thread;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;

import static java.lang.Thread.sleep;

public class UDPServer implements Runnable {

    @Override
    public void run() {
        try {
            // 创建UDP套接字并绑定到指定端口
            DatagramSocket serverSocket = new DatagramSocket(12580);

            System.out.println("UDP服务器已启动，等待客户端连接...");

            // 创建接收数据的缓冲区
            byte[] receiveData = new byte[1024];


            while (true) {
                // 创建接收数据报
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收数据报
                serverSocket.receive(receivePacket);

                // 解析接收到的数据
                JSONObject jsonObject = JSON.parseObject(new String(receivePacket.getData()));
                // 格式化输出json字符串
                System.out.printf("\n[%s][UDP][端口:%d]收到服务器[%s]的数据包：\n%s\n", getTime(), 12580, receivePacket.getAddress(), jsonObject.toString(JSONWriter.Feature.PrettyFormat));

                //根据接受的数据进行对应操作并得到一个返回的json
                Thread myfunction = new Thread(new MyFunction(receivePacket, serverSocket));
                myfunction.start();
                sleep(50);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(System.currentTimeMillis());
    }
}

